// 分区管理相关功能模块

// 加载分区列表
function loadPartitionList() {
    fetch('../BlogMake.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'action=get_site_config'
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const partitions = data.data.partitions || [];
                const partitionList = document.getElementById('partition-list');

                // 清空列表
                partitionList.innerHTML = '';

                if (partitions.length === 0) {
                    partitionList.innerHTML = `
                <div class="placeholder">
                    <i class="fas fa-folder-open"></i>
                    <p>暂无分区</p>
                    <button class="btn btn-primary mt-2" onclick="openPartitionModal()">创建分区</button>
                </div>
                `;
                } else {
                    // 显示分区列表
                    partitions.forEach(partition => {
                        const partitionCard = document.createElement('div');
                        partitionCard.className = 'partition-card mb-4 border rounded-lg p-4 shadow-sm';
                        partitionCard.innerHTML = `
  <div class="partition-header">
    <h3 class="partition-title">${partition.title}</h3>
    <div class="partition-actions">
      <button class="btn btn-secondary btn-sm" onclick="openPartitionModal(${partition.id})">编辑</button>
      <button class="btn btn-danger btn-sm" onclick="deletePartition(${partition.id})">删除</button>
    </div>
  </div>
  <p class="partition-description">${partition.description || '无描述'}</p>
  <hr class="partition-divider my-4 border-t-2 border-gray-200">
  <div class="partition-stats">
    <span class="partition-post-count">文章数量: <span class="count">0</span></span>
  </div>
`;
                        partitionList.appendChild(partitionCard);
                    });

                    // 添加创建分区按钮
                    const addButton = document.createElement('div');
                    addButton.className = 'text-center mt-4';
                    addButton.innerHTML = `<button class="btn btn-primary" onclick="openPartitionModal()">创建新分区</button>`;
                    partitionList.appendChild(addButton);
                }
            } else {
                showStatus('加载分区列表失败: ' + data.message, 'error');
            }
        })
        .then(() => {
            // 加载博客列表以更新文章计数
            return fetch('../BlogMake.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'action=get_blog_list'
            });
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const blogList = data.data || [];
                const partitionCards = document.querySelectorAll('.partition-card');

                partitionCards.forEach(card => {
                    // 从按钮onclick属性中提取分区ID
                    const editBtn = card.querySelector('button[onclick^="openPartitionModal"]');
                    const partitionId = parseInt(editBtn.getAttribute('onclick').match(/\d+/)[0]);
                    const count = blogList.filter(post => post.partition === partitionId).length;

                    // 更新文章数量
                    card.querySelector('.partition-post-count .count').textContent = count;
                });
            }
        })
        .catch(error => {
            console.error('加载分区列表失败:', error);
            showStatus('加载分区列表失败', 'error');
        });
}

// 打开分区模态框
function openPartitionModal(partitionId = null) {
    document.getElementById('partition-id').value = partitionId || '';
    document.getElementById('partition-title').value = '';
    document.getElementById('partition-description').value = '';
    document.getElementById('partition-modal').style.display = 'flex';
    document.getElementById('partition-modal-title').textContent = partitionId ? '编辑分区' : '创建分区';

    if (partitionId) {
        // 加载分区信息
        fetch('../BlogMake.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'action=get_site_config'
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const partitions = data.data.partitions || [];
                    const partition = partitions.find(p => p.id === partitionId);

                    if (partition) {
                        document.getElementById('partition-id').value = partition.id;
                        document.getElementById('partition-title').value = partition.title;
                        document.getElementById('partition-description').value = partition.description || '';
                    } else {
                        showStatus('未找到该分区', 'error');
                    }
                } else {
                    showStatus('加载分区信息失败: ' + data.message, 'error');
                }
            });
    }
}

// 保存分区
function savePartition() {
    const partitionId = document.getElementById('partition-id').value;
    const title = document.getElementById('partition-title').value;
    const description = document.getElementById('partition-description').value;

    if (!title) {
        showStatus('分区标题不能为空', 'error');
        return;
    }

    fetch('../BlogMake.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'action=save_partition&id=' + (partitionId || '') +
            '&title=' + encodeURIComponent(title) +
            '&description=' + encodeURIComponent(description)
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('partition-modal').style.display = 'none';
                loadPartitionList();
                loadBlogList();
                showStatus('分区保存成功', 'success');
            } else {
                showStatus('保存分区失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('保存分区失败:', error);
            showStatus('保存分区失败', 'error');
        });
}

// 删除分区
function deletePartition(partitionId) {
    if (!confirm('确定要删除这个分区吗？分区下的文章将被移至未分类。')) {
        return;
    }

    fetch('../BlogMake.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'action=delete_partition&id=' + partitionId
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadPartitionList();
                loadBlogList();
                showStatus('分区删除成功', 'success');
            } else {
                showStatus('删除分区失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('删除分区失败:', error);
            showStatus('删除分区失败', 'error');
        });
}